package com.zp.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * package the MD5 encryption algorithm
 * 
 * @since 1.0
 * 
 * @version 1.0
 * 
 * @author chenlijun08@gmail.com
 * 
 * @date 2014/1/21
 * 
 */

public class MD5Util {

	private static final Log logger = LogFactory.getLog(MD5Util.class);

	/**
	 * encrypt the password
	 * 
	 * @param password the String value
	 * 
	 * @return get the password which is encrypted
	 * 
	 * @exception NoSuchAlgorithmException if the argument is not allowed
	 */
	public static String MD5password(String password) {

		String str = null;
		int i;
		StringBuffer buf = new StringBuffer("");
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			try {
				messageDigest.update(password.getBytes("UTF-8"));
			} catch (UnsupportedEncodingException e) {
				logger.error("unsupport UTF-8 exception");
				e.printStackTrace();
			}
		} catch (NoSuchAlgorithmException e) {
			logger.error("NoSuchAlgorithmException caught!");
			e.printStackTrace();
			System.exit(Constant.NEGATIVE_ONE);
		}
		byte b[] = messageDigest.digest();
		for (int offset = Constant.ZERO; offset < b.length; offset++) {
			i = b[offset];
			if (i < Constant.ZERO)
				i += Constant.MD5_MAX_INDEX;
			if (i < Constant.MD5_DIGIT_NUM)
				buf.append("0");
			buf.append(Integer.toHexString(i));
		}
		str = buf.toString();

		return str;
	}
}
